package com.lagou.homework142;

import java.io.File;
import java.io.IOException;

/**
 * 实现将指定目录中的所有内容删除，包含子目录中的内容都要全部删除
 */
public class FileDeleteTest {
    public static String rootPath = "E:\\homework142";

    public static void main(String[] args) {
        try {

            System.out.println("创建前遍历...");
            find(rootPath);
            System.out.println("-----------------------");

            createFile();

            System.out.println("创建后遍历...");
            find(rootPath);
            System.out.println("-----------------------");

            System.out.println("开始删除...");
            delete(new File(rootPath));
            System.out.println("-----------------------");

            System.out.println("删除后遍历...");
            find(rootPath);
            System.out.println("-----------------------");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //递归删除
    public static boolean delete(File file) {
        if (file.isDirectory()) {
            String[] children = file.list();
            if (children != null)
                for (String child : children) {
                    boolean success = delete(new File(file, child));
                    if (!success) {
                        return false;
                    }
                }
        }

        if (file.getAbsolutePath().equals(rootPath))
            return true;
        // 目录此时为空，可以删除
        System.out.println("正在删除：" + file.getAbsolutePath());
        return file.delete();

    }

    //遍历
    public static void find(String path) {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length > 0) {
                for (File file2 : files) {
                    System.out.println(file2.getAbsolutePath());
                    if (file2.isDirectory()) {
                        find(file2.getAbsolutePath());
                    }
                }
            }
//            else System.out.println(file.getAbsolutePath() + ", 没有文件或目录~");
        } else {
            System.out.println("文件不存在!");
        }
    }

    //生成文件进行测试
    public static void createFile() throws IOException {
        System.out.println("创建文件以及目录...");
        File file = new File(rootPath);
        if (!file.exists())
            file.mkdirs();
        file = new File(rootPath + "/a.txt");
        file.createNewFile();

        file = new File(rootPath + "/目录一");
        file.mkdir();

        file = new File(file.getPath() + "/目录一的文件.txt");
        file.createNewFile();

        file = new File(rootPath + "/目录二");
        file.mkdir();

        System.out.println("-----------------------");
    }


}
